package com.linkoog.devtools.generate.singleton;

import com.intellij.codeInsight.generation.actions.BaseGenerateAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;

/**
 */
public class SingletonAction extends BaseGenerateAction {
    public SingletonAction() {
        super(null);
    }


    @Override
    public void actionPerformed(AnActionEvent event) {
        Project project = event.getProject();
        if (project == null) return;

        PsiFile psiFile = event.getData(LangDataKeys.PSI_FILE);
        if (psiFile == null) return;

        Editor editor = event.getData(PlatformDataKeys.EDITOR);
        if (editor == null) return;

        PsiElement element = psiFile.findElementAt(editor.getCaretModel().getOffset());
        PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
        if (psiClass == null) return;

        if (psiClass.getNameIdentifier() == null) return;

        BuildContext buildContext = new BuildContext();
        buildContext.setProject(project);
        buildContext.setPsiFile(psiFile);
        buildContext.setEditor(editor);
        buildContext.setPsiClass(psiClass);

        PatternPickerDialog dialog = new PatternPickerDialog(buildContext);
        dialog.setVisible(true);
    }


    @Override
    public void update(@NotNull AnActionEvent event) {
        Project project = event.getProject();
        PsiFile psiFile = event.getData(LangDataKeys.PSI_FILE);
        Editor editor = event.getData(PlatformDataKeys.EDITOR);
        if (project == null || psiFile == null || editor == null){
            event.getPresentation().setVisible(false);
            return;
        }

        PsiElement element = psiFile.findElementAt(editor.getCaretModel().getOffset());
        PsiClass psiClass = PsiTreeUtil.getParentOfType(element, PsiClass.class);
        if (psiClass != null) {
            event.getPresentation().setVisible(true);
        } else {
            event.getPresentation().setVisible(false);
        }
    }
}
